package com.goldenautumn.prefabricate.activity.mine.order

import androidx.activity.viewModels
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ActivityUtils
import com.goldenautumn.prefabricate.R
import com.goldenautumn.prefabricate.activity.cart.SettlementGoodsAdapter
import com.goldenautumn.prefabricate.activity.mine.adapter.ImgSelectAdapter
import com.goldenautumn.prefabricate.business.entity.ApplyRefundGoods
import com.goldenautumn.prefabricate.business.entity.GoodsInfoVO
import com.goldenautumn.prefabricate.business.entity.GoodsSkuVo
import com.goldenautumn.prefabricate.business.entity.ImageSelectVo
import com.goldenautumn.prefabricate.business.entity.OrderDetailsInfoVo
import com.goldenautumn.prefabricate.business.order.OrderStatusUiState
import com.goldenautumn.prefabricate.business.order.OrderViewModel
import com.goldenautumn.prefabricate.business.user.LoadingUiState
import com.goldenautumn.prefabricate.databinding.ActivityApplyRefundBinding
import com.goldenautumn.prefabricate.utils.Constants
import com.goldenautumn.prefabricate.utils.Constants.BUSINESS_PAGE_DATA
import com.goldenautumn.prefabricate.utils.ImageSelectUtils
import com.goldenautumn.prefabricate.utils.ImageSelectUtils.dynamicAlbumCamera
import com.goldenautumn.prefabricate.utils.onCenterToast
import com.gyf.immersionbar.ImmersionBar
import com.luck.picture.lib.entity.LocalMedia
import kotlinx.coroutines.isActive
import kotlinx.coroutines.selects.select
import qncx.external.common.base.BaseActivity
import qncx.external.common.compat.gone
import qncx.external.common.utils.intent
import qncx.external.common.widget.dialog.PromptDialog

class ApplyRefundActivity : BaseActivity<ActivityApplyRefundBinding>() {

    private val mOrderModel by viewModels<OrderViewModel>()

    private val mImgAdapter by lazy {
        ImgSelectAdapter()
    }

    private val mAdapter by lazy {
        SettlementGoodsAdapter()
    }

    var type:Int? = null

    private val orderID:String?
        get() = intent.getStringExtra(BUSINESS_PAGE_DATA)

    private val applyRefund: ApplyRefundGoods?
        get() = intent.getSerializableExtra("DATA") as ApplyRefundGoods

    override fun getLayoutId(): Int = R.layout.activity_apply_refund

    override suspend fun main() {
        ImmersionBar.setTitleBar(this, mBinding.toolbar)
        initToolbarNav(mBinding.toolbar)

        mBinding.goodsRv.layoutManager = LinearLayoutManager(this)
        mBinding.imageView.layoutManager = GridLayoutManager(this,3)
        mBinding.goodsRv.adapter = mAdapter
        mBinding.imageView.adapter = mImgAdapter

        mImgAdapter.submitList(arrayListOf(ImageSelectVo(type = 1)))

        mImgAdapter.addOnItemChildClickListener(R.id.subBtn) { adapter,_,position ->
            adapter.removeAt(position)
            adapter.notifyItemChanged(position)
        }

        mImgAdapter.addOnItemChildClickListener(R.id.shapeLinearLayout6) { _,_,_ ->
            var oldArr = ArrayList<LocalMedia>()
            mImgAdapter.items.forEach { it.img?.let { oldArr.add(it) } }
            dynamicAlbumCamera(this@ApplyRefundActivity,oldArr) {
                var arr = ArrayList<ImageSelectVo>()
                it.forEach { arr.add(ImageSelectVo(type = 2,img = it)) }
                arr.add(ImageSelectVo(type = 1))
                mImgAdapter.submitList(arr)
            }
        }

        mBinding.status.setOnClickListener {
            ApplyRefundDialog {
                type = it.type
                mBinding.status.setRightString(it.title)
            }.onShow(supportFragmentManager.beginTransaction())
        }

        mBinding.orderSn.text = String.format(getString(R.string.order_sn),"$orderID")
        mBinding.totalCount.text = String.format(getString(R.string.unit),"${applyRefund?.total_num}")
        mBinding.totalPrice.text = String.format(getString(R.string.currency), "${applyRefund?.goods_sku?.goods_price}")

        var goods = ArrayList<GoodsInfoVO>()
        goods.add(
            GoodsInfoVO(
                goods_id = applyRefund?.goods_id,
                goods_image = applyRefund?.goods_image,
                goods_name = applyRefund?.goods_name,
                goods_sku = GoodsSkuVo(goods_id = applyRefund?.goods_sku?.goods_id,goods_attr = applyRefund?.goods_sku?.goods_attr,goods_price = applyRefund?.goods_sku?.goods_price, spec_sku_id = applyRefund?.goods_sku?.spec_sku_id),
                total_num = applyRefund?.total_num
            )
        )
        mAdapter.submitList(goods)

        mBinding.submitBtn.isEnabled = true
        mBinding.submitBtn.setOnClickListener {
            var content = mBinding.input.text.toString()
            if(type == null) {
                onCenterToast(getString(R.string.select_after_sales))
                mBinding.submitBtn.reset()
                return@setOnClickListener
            }
            if(content.isNullOrEmpty()) {
                mBinding.submitBtn.reset()
                onCenterToast(getString(R.string.please_enter_reason))
                return@setOnClickListener
            }
            mOrderModel.onOrderRefund("$type","${applyRefund?.goods_id}",content)
        }

        while (isActive) {
            select {
                mOrderModel.orderStatusUiState.onReceive {
                    when (it) {
                        is OrderStatusUiState.ActionMsg -> {
                            if(it.msg == null) {
                                mBinding.submitBtn.showSucceed()
                                setResult(RESULT_OK)
                                startActivity(ApplyRefundResultActivity::class.intent)
                                ActivityUtils.finishActivity(OrderDetailsActivity::class.java)
                                finish()
                            } else {
                                mBinding.submitBtn.showError(1500)
                                onCenterToast("${it.msg}")
                            }
                        }
                        else -> {}
                    }
                }
            }
        }

    }

}